{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>大纲<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#模块功能\" data-toc-modified-id=\"模块功能-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>模块功能</a></span></li><li><span><a href=\"#获取线程ID\" data-toc-modified-id=\"获取线程ID-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>获取线程ID</a></span></li><li><span><a href=\"#协程实现生产者、消费者\" data-toc-modified-id=\"协程实现生产者、消费者-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>协程实现生产者、消费者</a></span></li></ul></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模块功能\n",
    "实现多线程多进程的异步并发\n",
    "\n",
    "特点：\n",
    "    1. 继承自`Executor`（不能直接使用，可以使用它的子类）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T06:17:57.229117Z",
     "start_time": "2018-05-10T06:16:57.129063Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'http://www.cnn.com/' page is 167671 bytes\n",
      "'http://www.bbc.co.uk/' page is 293466 bytes\n",
      "'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno -2] Name or service not known>\n",
      "'http://europe.wsj.com/' generated an exception: <urlopen error [Errno 111] Connection refused>\n",
      "'http://www.foxnews.com/' generated an exception: <urlopen error [Errno 101] Network is unreachable>\n"
     ]
    }
   ],
   "source": [
    "import concurrent.futures\n",
    "import urllib.request\n",
    "\n",
    "URLS = ['http://www.foxnews.com/',\n",
    "        'http://www.cnn.com/',\n",
    "        'http://europe.wsj.com/',\n",
    "        'http://www.bbc.co.uk/',\n",
    "        'http://some-made-up-domain.com/']\n",
    "\n",
    "# Retrieve a single page and report the URL and contents\n",
    "def load_url(url, timeout):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "# We can use a with statement to ensure threads are cleaned up promptly\n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n",
    "    # Start the load operations and mark each future with its URL\n",
    "    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n",
    "    for future in concurrent.futures.as_completed(future_to_url):\n",
    "        url = future_to_url[future]\n",
    "        try:\n",
    "            data = future.result()\n",
    "        except Exception as exc:\n",
    "            print('%r generated an exception: %s' % (url, exc))\n",
    "        else:\n",
    "            print('%r page is %d bytes' % (url, len(data)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 获取线程ID"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-11T04:44:36.492594Z",
     "start_time": "2018-05-11T04:44:36.482506Z"
    },
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name:wangkaixuan,threading:140216151553792\n",
      "name:chengangrong,threading:140216151553792\n",
      "name:longhao,threading:140216151553792\n",
      "name:longhao1,threading:140216143161088\n",
      "name:longhao2,threading:140216159946496\n",
      "返回值：name:longhao3,threading:140216151553792\n",
      " <Future at 0x7f869e696cf8 state=finished returned str>\n",
      "返回值： <Future at 0x7f869e696550 state=finished returned str>\n",
      "返回值： <Future at 0x7f869e696780 state=finished returned str>\n",
      "返回值： <Future at 0x7f869e6b8470 state=finished returned str>\n",
      "返回值： <Future at 0x7f869e6b8048 state=finished returned str>\n",
      "返回值： <Future at 0x7f869e6b8cf8 state=finished returned str>\n"
     ]
    }
   ],
   "source": [
    "import concurrent.futures\n",
    "import os\n",
    "import time\n",
    "import threading\n",
    "\n",
    "def p(name):\n",
    "    print('name:%s,threading:%s' % (name,threading.get_ident()))\n",
    "    return name\n",
    "    \n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=5) as e:\n",
    "    obj = {e.submit(p,name):name for name in ['wangkaixuan','chengangrong','longhao','longhao1','longhao2','longhao3']}\n",
    "    for i in obj:\n",
    "        print('返回值：',i)    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 协程实现生产者、消费者\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T07:38:15.765891Z",
     "start_time": "2018-05-10T07:38:15.761788Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "生产了数字: 1\n",
      "消费了数字: 1\n",
      "消费者返回了: 1\n",
      "生产了数字: 2\n",
      "消费了数字: 2\n",
      "消费者返回了: 2\n",
      "生产了数字: 3\n",
      "消费了数字: 3\n",
      "消费者返回了: 3\n",
      "生产了数字: 4\n",
      "消费了数字: 4\n",
      "消费者返回了: 4\n",
      "生产了数字: 5\n",
      "消费了数字: 5\n",
      "消费者返回了: 5\n"
     ]
    }
   ],
   "source": [
    "def consumer():\n",
    "    r = ''\n",
    "    while True:\n",
    "        n = yield r\n",
    "        if not n:\n",
    "            return \n",
    "        print('消费了数字:',n)\n",
    "        r = '200 OK'\n",
    "\n",
    "def produce(c):\n",
    "    c.send(None)\n",
    "    n = 0\n",
    "    while n < 5:\n",
    "        n = n + 1\n",
    "        print('生产了数字:',n)\n",
    "        r = c.send(n)\n",
    "        print('消费者返回了:',n)\n",
    "    c.close()\n",
    "\n",
    "c = consumer()    \n",
    "produce(c)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda all lib",
   "language": "python",
   "name": "base"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "大纲",
   "title_sidebar": "目录",
   "toc_cell": true,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
